<template>
  <div style="padding: 30px">
    <div>
      <h3 style="text-align: center">
        快递信息 <span style="font-size: 14px">(扫码录入)</span>
      </h3>
      <!-- <p>扫描单号：{{ barcode }}</p> -->
      <div v-if="parcelInfo">
        <div style="display: flex">
          <div style="width: 24%; text-align: center">
            <p style="text-align: center; font-size: 18px">服务</p>
            <p>必选服务</p>
            <span v-if="bixuanf.length" style="color: #595757">
              {{ shanx(bixuanf, parcelInfo.requiredContent)[0].dictLabel }}
            </span>
            <p>可选服务</p>
            <span v-if="kexuanf.length" style="color: #595757">
              {{ shanxx(kexuanf, parcelInfo.choosableContent) }}
            </span>
            <p>打包要求</p>
            <span style="color: #595757">
              {{ parcelInfo.askFor }}
            </span>
          </div>
          <div style="width: 24%; text-align: center">
            <p style="text-align: center; font-size: 18px">国际订单</p>
            <p>
              订单编号:
              <span style="color: #595757">
                {{ parcelInfo.postingNumber }}
              </span>
            </p>
            <p>
              条 形 码:
              <span style="color: #595757">
                {{ parcelInfo.trackingNumber }}
              </span>
            </p>
            <p>
              国际面单:
              <span style="color: #595757">
                <a style="color: blue" target="_blank" :href="parcelInfo.pdfUrl"
                  >下载</a
                >
              </span>
            </p>
          </div>
          <div style="width: 24%; text-align: center">
            <p style="text-align: center; font-size: 18px">商品信息</p>
            <p>商品图片</p>
            <el-image
              v-for="iten in parcelInfo.orderProductList[0].productImages.split(
                ','
              )"
              :key="iten"
              style="width: 100px; height: 100px"
              :src="iten"
              :preview-src-list="srcList"
            >
            </el-image>
            <p>
              商品数量:
              <span style="color: #595757">
                {{ parcelInfo.orderProductList[0].productCount }}
              </span>
            </p>
            <p>商品描述:</p>
            <span style="color: #595757">
              {{ parcelInfo.orderProductList[0].contentInspection }}
            </span>
          </div>
          <div style="width: 24%; text-align: center">
            <p style="text-align: center; font-size: 18px">打包来源</p>
            商品来源: <span style="color: #595757"> 国内快递 </span>
            <p style="text-align: center; font-size: 18px">快递单号</p>
            商品来源:
            <span style="color: #595757">
              {{ parcelInfo.orderProductList[0].courierNumber }}
            </span>
          </div>
        </div>
        <p style="text-align: center">
          <el-button type="primary" @click="biangegn">完成打包</el-button>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import { cahx, bixuan, kexuan, laiyuan, gengxin, xiazai } from "@/api/login.js";
export default {
  data() {
    return {
      barcode: "", // 用于存储扫描到的条码数据
      parcelInfo: null,
      srcList: [],
      bixuanf: [],
      kexuanf: [],
    };
  },
  created() {
    this.getbixuan();
    this.laiya();
  },
  methods: {
    biangegn() {
      gengxin({ id: this.parcelInfo.id, status: 0 }).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: "打包完成！",
            type: "success",
          });
        }
      });
    },
    async laiya() {
      const { data } = await laiyuan();
    },
    shanx(data, e) {
      return data.filter((item) => e == item.dictValue);
    },
    shanxx(data, e) {
      let result = "";
      if (e) {
        result = e
          .split(",")
          .map((item) => {
            let found = data.filter((i) => item == i.dictValue)[0];
            return found ? found.dictLabel : "";
          })
          .filter(Boolean) // 过滤掉空字符串（如果任何dictValue没有找到匹配项）
          .join("\n");
      }
      return result;
    },
    async getbixuan() {
      const { data } = await bixuan();

      const row = await kexuan();
      this.kexuanf = row.data;
      this.bixuanf = data;
    },
    handleKeydown(event) {
      // 如果按下的是回车键
      if (event.key === "Enter") {
        if (this.barcode.length > 0) {
          console.log(this.barcode);
          this.fetchParcelInfo(this.barcode); // 获取条码对应的快递信息
          this.barcode = ""; // 清空条码数据
        }
      } else if (/^[a-zA-Z0-9]$/.test(event.key)) {
        // 只处理字母和数字键
        this.barcode += event.key;
      }
    },
    async fetchParcelInfo(barcode) {
      try {
        const { data } = await cahx({ courierNumber: barcode });
        this.parcelInfo = data;
        this.srcList =
          this.parcelInfo.orderProductList[0].productImages.split(",");
        // 获取代理后的 PDF 文件
        const response = await xiazai(this.parcelInfo.pdfUrl);
        console.log(response);
        const blob = new Blob([response], { type: "application/pdf" });
        console.log("Blob created:", blob);
        const pdfUrl = URL.createObjectURL(blob);
        // 创建一个隐藏的 iframe 元素
        console.log(pdfUrl);
        const iframe = document.createElement("iframe");

        iframe.style.display = "none";
        iframe.src = pdfUrl;
        document.body.appendChild(iframe);

        // 加载完成后触发打印功能
        // this.$nextTick(() => {
        //   iframe.onload = () => {
        //     console.log("PDF loaded in iframe");
        //     iframe.contentWindow.focus();
        //     iframe.contentWindow.print();
        //     document.body.removeChild(iframe); // 打印完成后移除 iframe 元素
        //   };
        // });
      } catch (error) {
        console.error("Error fetching parcel info:", error);
      }
    },
  },
  mounted() {
    window.addEventListener("keydown", this.handleKeydown); // 在窗口范围内监听键盘事件
  },
  beforeDestroy() {
    window.removeEventListener("keydown", this.handleKeydown); // 移除键盘事件监听器，防止内存泄漏
  },
};
</script>

<style scoped>
a {
  color: #595757;
}
/* 样式可以根据需要进行调整 */
</style>
